package org.liang.auth.service.impl;

import org.liang.auth.dto.LoginDTO;
import org.liang.auth.service.ILoginService;
import org.liang.base.context.LoginContext;
import org.liang.system.domain.Employee;
import org.liang.system.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IEmployeeService employeeService;

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        if(Objects.isNull(loginDTO.getUsername()) || Objects.isNull(loginDTO.getPassword())){
            throw new RuntimeException("用户名或密码不能为空!");
        }
        //查询用户或密码对不对
        Employee employee = employeeService.selectByUserName(loginDTO);
        if(Objects.isNull(employee)){
            throw new RuntimeException("用户名或密码错误!");
        }
        if(!employee.getPassword().equals(loginDTO.getPassword().trim())){
            throw new RuntimeException("用户名或密码错误!");
        }

        String token = UUID.randomUUID().toString();

        //存后台
        LoginContext.loginMap.put(token,employee);

        //考虑安全
        employee.setPassword("");
        //存前端
        HashMap<String, Object> data = new HashMap<>();
        data.put("token",token);
        data.put("user",employee);
        return data;
    }
}
